/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Presentacion;

import AccesoADatos.GlobalException;
import AccesoADatos.NoDataException;
import AccesoADatos.ServicioTableSpace;
import Logica.DatosConexion;
import Logica.Estrategia;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import java.io.*;

/**
 *
 * @author Carlos Arroyo
 */
public class CreateStrategy extends javax.swing.JFrame {

    private DatosConexion dac;
    private ServicioTableSpace ser;
    private Principal principal;
    private String servidor;
    private Strategy stry;

    public CreateStrategy(DatosConexion dac, Principal pp, String name, Strategy sss) throws GlobalException, NoDataException {
        initComponents();
        this.setTitle("Create new Strategy.");
        this.servidor = name;
        this.principal = pp;
        this.dac = dac;
        this.stry = sss;
        ser = new ServicioTableSpace(dac.getUser(), dac.getPass(), dac.getIp(), dac.getPort(), dac.getDb(), null);
        this.cargarLista();
        this.dispose();


        this.jTable1.getTableHeader().setReorderingAllowed(false);
        this.jTable2.getTableHeader().setReorderingAllowed(false);
        this.setResizable(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jComboBox1 = new javax.swing.JComboBox();
        buttonGroup1 = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jComboBox2 = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel1.setText("New Strategy");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(69, 37, -1, -1));

        jLabel2.setText("Name:");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(69, 97, -1, -1));

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 94, 168, -1));

        jLabel3.setText("Backup Type:");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(69, 157, -1, -1));

        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Full", "Incremental" }));
        getContentPane().add(jComboBox2, new org.netbeans.lib.awtextra.AbsoluteConstraints(152, 154, -1, -1));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "TableSpace", "Selected"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(69, 228, -1, 270));

        buttonGroup1.add(jRadioButton1);
        jRadioButton1.setText("ALL");
        getContentPane().add(jRadioButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 187, -1, -1));

        buttonGroup1.add(jRadioButton2);
        jRadioButton2.setText("PARTIAL");
        getContentPane().add(jRadioButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(569, 187, -1, -1));

        jButton1.setText("Create");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(53, 627, -1, -1));

        jButton2.setText("Cancel");
        getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(136, 627, -1, -1));

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"12:00 am", null, null, null, null, null, null, null},
                {"1:00 am", null, null, null, null, null, null, null},
                {"2:00 am", null, null, null, null, null, null, null},
                {"3:00 am", null, null, null, null, null, null, null},
                {"4:00 am", null, null, null, null, null, null, null},
                {"5:00 am", null, null, null, null, null, null, null},
                {"6:00 am", null, null, null, null, null, null, null},
                {"7:00 am", null, null, null, null, null, null, null},
                {"8:00 am", null, null, null, null, null, null, null},
                {"9:00 am", null, null, null, null, null, null, null},
                {"10:00 am", null, null, null, null, null, null, null},
                {"11:00 am", null, null, null, null, null, null, null},
                {"12:00 pm", null, null, null, null, null, null, null},
                {"1:00 pm", null, null, null, null, null, null, null},
                {"2:00 pm", null, null, null, null, null, null, null},
                {"3:00 pm", null, null, null, null, null, null, null},
                {"4:00 pm", null, null, null, null, null, null, null},
                {"5:00 pm", null, null, null, null, null, null, null},
                {"6:00 pm", null, null, null, null, null, null, null},
                {"7:00 pm", null, null, null, null, null, null, null},
                {"8:00 pm", null, null, null, null, null, null, null},
                {"9:00 pm", null, null, null, null, null, null, null},
                {"10:00 pm", null, null, null, null, null, null, null},
                {"11:00 pm", null, null, null, null, null, null, null}
            },
            new String [] {
                "Schedule", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, true, true, true, true, true, true, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jTable2);

        getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 230, 568, 410));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        
        boolean exito = true;
        if (jTextField1.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Strategy name error");
            exito = false;
        }
        ArrayList list = new ArrayList();
        for (int i = 0; i < this.jTable1.getModel().getRowCount(); i++) {
            if (this.jTable1.getModel().getValueAt(i, 1) == true) {
                list.add(this.jTable1.getModel().getValueAt(i, 0));
            }
        }

        ArrayList<String> schedule = new ArrayList();
        for (int j = 1; j < this.jTable2.getModel().getColumnCount(); j++) {
            for (int i = 0; i < this.jTable2.getModel().getRowCount(); i++) {
                if (this.jTable2.getModel().getValueAt(i, j) == true) {
                    String hora = jTable2.getModel().getValueAt(i, 0) + "  " + jTable2.getColumnName(j);
                    schedule.add(hora);
                }
            }
        }

        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i).toString());
        }

        if (list.isEmpty()) {
            JOptionPane.showMessageDialog(null, "No Table Spaces Selected...!!!");
            exito = false;
        }

        if (!jRadioButton1.isSelected() && !jRadioButton2.isSelected()) {
            JOptionPane.showMessageDialog(null, "ALL and PARTIAL are not selected.");
            exito = false;
        }
        
        if(schedule.isEmpty()){
            JOptionPane.showMessageDialog(null, "Schedule is not selected.");
            exito = false;
        }

        if (exito) {
            String n = "";
            if (jRadioButton1.isSelected()) {
                n = "ALL";
            }
            if (jRadioButton2.isSelected()) {
                n = "PARTIAL";
            }
            //crearRMAN(jTextField1.getText(), jComboBox2.getSelectedItem().toString(), n, list);
            String n1 = jTextField1.getText();
            String n2 = jComboBox2.getSelectedItem().toString();
            boolean ty = false;
            if (n2.equals("Full")) {
                ty = true;
            }
            String n3 = n1 + "RMAN.rman";
            String horario="";
            for(int i = 0; i < schedule.size();i++){
                horario += schedule.get(i);
                horario += "\n";
            }
            
            //JOptionPane.showMessageDialog(this, horario);
            Estrategia est = new Estrategia(n1, ty, n3, true, horario, servidor);
            
            this.principal.getEstrategias().add(est);
            crearRMAN(jTextField1.getText(), jComboBox2.getSelectedItem().toString(), n, list);
            try {
                this.principal.actualizarArchivo();
                this.stry.cargarTabla();
            } catch (FileNotFoundException ex) {
                JOptionPane.showMessageDialog(this, "error guardar 1");
            } catch (IOException ex) {
            }


            JOptionPane.showMessageDialog(this, est.toString() + "\n\n");
            JOptionPane.showMessageDialog(this, "NEW RMAN CREATED");
        }

        this.dispose();
    }//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables

    public DatosConexion getDac() {
        return dac;
    }

    /**
     * @param dac the dac to set
     */
    public void setDac(DatosConexion dac) {
        this.dac = dac;
    }

    public void cargarLista() throws GlobalException, NoDataException {
        ArrayList<String> list = new ArrayList();
        
        if(this.servidor.equals("LOCALHOST")){
            list = (ArrayList<String>) ser.listarTS();
        }else{
            list = (ArrayList<String>) ser.listarTS(this.servidor);
        }
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();

        for (int i = 0; i < list.size(); i++) {

            model.addRow(new Object[]{list.get(i)});
        }
    }

    public void crearRMAN(String nombre, String tipo, String com, ArrayList list) {
        File f;
        FileWriter escritorArchivo;
        try {
            f = new File(nombre + "RMAN.rman");
            escritorArchivo = new FileWriter(f);
            BufferedWriter bw = new BufferedWriter(escritorArchivo);
            PrintWriter salida = new PrintWriter(bw);

            if (tipo.equals("Incremental") && (com.equals("ALL"))) {
                salida.write("connect target sys/sysdba@xe\n");
                salida.write("\n\n");
                salida.write("SPOOL LOG to 'C:\\Rman\\FullBackUp\\'" + nombre + ".txt' append;\n");
                salida.write("run{\n");
                salida.write("ALLOCATE CHANNEL database_sid TYPE DISK FORMAT 'C:\\Rman\\FullBackUp\\RmanIncAll';\n");
                salida.write("configure controlfile autobackup format for device type disk to 'C:\\Rman\\FullBackUp\\AutoBackUpIncAll%F';\n");
                salida.write("configure controlfile autobackup on;\n");
                salida.write("BACKUP INCREMENTAL LEVEL 0 DATABASE;\n");
                salida.write("RELEASE CHANNEL database_sid;\n");
                salida.write("}\n\n");
            }
            if (tipo.equals("Incremental") && (com.equals("PARTIAL"))) {
                for (int i = 0; i < list.size(); i++) {

                    salida.write("connect target sys/sysdba@xe\n");
                    salida.write("\n\n");
                    salida.write("SPOOL LOG to 'C:\\Rman\\FullBackUp\\'" + nombre + ".txt' append;\n");
                    salida.write("run{\n");
                    salida.write("ALLOCATE CHANNEL database_sid TYPE DISK FORMAT 'C:\\Rman\\FullBackUp\\RmanIncAll';\n");
                    salida.write("configure controlfile autobackup format for device type disk to 'C:\\Rman\\FullBackUp\\AutoBackUpIncAll%F';\n");
                    salida.write("configure controlfile autobackup on;\n");
                    salida.write("BACKUP INCREMENTAL LEVEL 0 tablespace " + list.get(i).toString() + ";\n");
                    salida.write("RELEASE CHANNEL database_sid;\n");
                    salida.write("}\n\n");
                }
            }
            if (tipo.equals("Full") && (com.equals("ALL"))) {
                salida.write("connect target sys/sysdba@xe\n");
                salida.write("\n\n");
                salida.write("RUN{\n");

                salida.write("ALLOCATE CHANNEL database_sid TYPE DISK;\n");
                salida.write("configure controlfile autobackup format for device type disk to 'C:\\Rman\\FullBackUp\\AutoBackUpIncAll%F';\n");
                salida.write("configure controlfile autobackup on;\n");
                salida.write("BACKUP TAG FULL_DB FORMAT 'C:\\Rman\\FullBackUp\\db_%t_%s.bk' (database);\n");
                salida.write("RELEASE CHANNEL database_sid;\n");
                salida.write("}\n\n");
            }
            if (tipo.equals("Full") && (com.equals("PARTIAL"))) {
                for (int i = 0; i < list.size(); i++) {
                    salida.write("connect target sys/sysdba@xe\n");
                    salida.write("\n\n");
                    salida.write("RUN{\n");

                    salida.write("ALLOCATE CHANNEL database_sid TYPE DISK;\n");
                    salida.write("configure controlfile autobackup format for device type disk to 'C:\\Rman\\FullBackUp\\AutoBackUpIncAll%F';\n");
                    salida.write("configure controlfile autobackup on;\n");
                    salida.write("BACKUP tablespace" + list.get(i).toString() + " FORMAT 'C:\\Rman\\FullBackUp\\%U' archivelog like '%arc_dest%';\n");
                    salida.write("RELEASE CHANNEL database_sid;\n");
                    salida.write("}\n\n");
                }
            }
            salida.close();
            bw.close();
        } catch (IOException e) {
            System.out.println("Error:" + e.getMessage());


        }

    }

    public Strategy getStry() {
        return stry;
    }

    public void setStry(Strategy stry) {
        this.stry = stry;
    }
}
